import fs from "fs"
import axios from 'axios'

const success = data => ({
    isSuccess: true,
    ...data
})

const error = msg => ({
    isSuccess: false,
    logText: msg
})

export function downloadFile(url, targetPath){
    return new Promise((resolve, reject) => {
        const start = Date.now();
        axios({
            method: 'get',
            url,
            responseType: 'stream'
        }).then(response => {
            const writer = fs.createWriteStream(targetPath)
            response.data.pipe(writer);
            writer.on('finish', () => {
                const duration = Date.now() - start;
                resolve(success({duration, url}))
            });
            writer.on('error', reject)
        }).catch(err => {
            resolve(error(err.message))
        })
    })
}